import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';
import 'package:toys_flutter/components/UserItem.dart';

/// 附近用户
class AttachmentUsers extends StatefulWidget {
  const AttachmentUsers({super.key});

  @override
  State<AttachmentUsers> createState() => _AttachmentUsersState();
}

class _AttachmentUsersState extends State<AttachmentUsers>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  List<dynamic> _list = [];
  int page = 1;
  bool isMore = true;
  bool showOpenVip = false;
  String showOpenVipMsg = '';

  @override
  void initState() {
    super.initState();
    getData();
  }

  void getData() async {
    var res = await Api.imNearbyUser({'page': page});
    if (res['code'] == 1) {
      // 更新数据
      setState(() {
        _list = res['data']['list'] ?? [];
        isMore = res['data']['more'] == 0 ? false : true;
      });
    }
    if (res['code'] == -2) {
      setState(() {
        showOpenVip = res['code'] == -2;
        showOpenVipMsg = res['msg'];
      });
    }
  }

  Future<void> onLoadMore() async {
    if (isMore == false) return;
    page++;
    var res = await Api.toysFans({'page': page});
    if (res['code'] == 1) {
      List<dynamic> newItems = res['data']['list'] ?? [];

      setState(() {
        _list = [..._list, ...newItems];
        isMore = res['data']['more'] == 0 ? false : true;
      });
    }
  }

  // 模拟数据刷新
  Future<void> _refreshData() async {
    try {
      getData();
    } catch (e) {
      TDToast.showIconText('失败',
          icon: TDIcons.error,
          direction: IconTextDirection.vertical,
          context: context);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (showOpenVip) {
      return Center(
        child: Column(
          children: [
            const SizedBox(height: 100),
            Text(showOpenVipMsg, style: const TextStyle(fontSize: 16)),
            Padding(
              padding: const EdgeInsets.fromLTRB(100, 20, 100, 20),
              child: TextButton(
                onPressed: () {},
                style: TextButton.styleFrom(
                  minimumSize: const Size(200, 50),
                  backgroundColor: Colors.blue,
                ),
                child: const Text('去开通'),
              ),
            )
          ],
        ),
      );
    }
    return RefreshableListView(
        enableLoadMore: true, // 启用上拉加载
        onRefresh: _refreshData, // 绑定刷新逻辑
        children: [
          ..._list.map((item) => Column(
                children: [UserItem(user: item), const SizedBox(height: 10)],
              )),
        ]);
  }
}
